import pymysql
import random
import time
import multiprocessing
import math
import gevent
from gevent import monkey; monkey.patch_all()

def insert_record(num, process):
    start_time = time.clock()
    mysql = pymysql.connect("localhost", "root", "", "test")
    cursor = mysql.cursor()
    i = 0

    while i <= num:
        print(f"{process},{i}")
        user_id = random.randint(0, 100000)
        order_id = random.randint(0, 100000)
        collection_id = random.randint(0, 100000)
        rank = random.randint(0, 2)
        version = random.randint(1, 3)
        created_at = int(time.time())

        sql = """
          insert into tb_collection_user_rank 
          set 
          user_id = {user_id},
          order_id = {order_id},
          rank = {rank},
          collection_id = {collection_id},
          created_at = {created_at},
          updated_at = 0,+
          version = {version}
        """.format(user_id=user_id, order_id=order_id, collection_id=collection_id, rank=rank, version=version,
                   created_at=created_at)

        cursor.execute(sql)
        i += 1
        # 此处节约20秒
        if i % 10000 == 0:
            mysql.commit()

    mysql.commit()
    print("{0},{1}".format(process, i))
    end_time = time.clock()
    print("进程{0}:执行{1}ms".format(process, math.ceil((end_time - start_time) * 1000)))


if __name__ == "__main__":
    # multiprocessing.freeze_support()
    start_time = time.clock()
    # pool = multiprocessing.Pool(processes=5)

    # for x in range(0, 10):
        # result = multiprocessing.Process(target=insert_record, args=(10000, x))
        # result.start()
    # pool.close()
    # pool.join()
    yields = [gevent.spawn(insert_record,num=10000,process=x) for x in range(0,10)]
    gevent.joinall(yields)

    end_time = time.clock()
    print("共用：{0}ms".format(math.ceil((end_time - start_time) * 1000)))
else:
    print("no main")
